package com.crazyktv.wcf.android;

import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;

public class Prefs extends PreferenceActivity implements
		OnPreferenceChangeListener {
	EditTextPreference prefIP, prefPort, prefDays;
	ListPreference refreshTime, numLen;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.settings);

		prefIP = (EditTextPreference) findPreference(getText(R.string.prefkey_ip));
		prefIP.setOnPreferenceChangeListener(this);
		prefIP.setSummary(prefIP.getText());

		prefPort = (EditTextPreference) findPreference(getText(R.string.prefkey_port));
		prefPort.setOnPreferenceChangeListener(this);
		prefPort.setSummary(prefPort.getText());

		prefDays = (EditTextPreference) findPreference(getText(R.string.prefkey_new_song_inner_days));
		prefDays.setOnPreferenceChangeListener(this);
		prefDays.setSummary(prefDays.getText());

		numLen = (ListPreference) findPreference(getText(R.string.prefkey_num_len));
		numLen.setOnPreferenceChangeListener(this);
		numLen.setSummary(numLen.getEntry());

		refreshTime = (ListPreference) findPreference(getText(R.string.prefkey_refresh_time));
		refreshTime.setOnPreferenceChangeListener(this);
		refreshTime.setSummary(refreshTime.getEntry());

	}

	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {
		return super.onPreferenceTreeClick(preferenceScreen, preference);
	}

	public boolean onPreferenceChange(Preference preference, Object newValue) {
		if (preference.getKey().equals(getText(R.string.prefkey_ip))) // 根據不同的key來辨別不同的Preference
			preference.setSummary(" " + newValue);
		else if (preference.getKey().equals(getText(R.string.prefkey_port)))
			preference.setSummary(" " + newValue);

		else if (preference.getKey().equals(
				getText(R.string.prefkey_new_song_inner_days)))
			preference.setSummary(" " + newValue);

		// 從Entry中對應顯示使用者選擇的item value
		else if (preference.getKey().equals(getText(R.string.prefkey_num_len)))
			preference.setSummary(" "
					+ ((ListPreference) preference).getEntries()[Integer
							.parseInt(newValue.toString())]);

		else if (preference.getKey().equals(
				getText(R.string.prefkey_refresh_time)))
			preference.setSummary(" "
					+ ((ListPreference) preference).getEntries()[Integer
							.parseInt(newValue.toString())]);

		return true;
	}
}
